<template>
  <div>
    <!-- 头部 -->
    <el-header class="header">
      <el-row type="flex" class="row-bg" justify="space-between">
        <!-- LOGO -->
        <el-col :span="12">
          <div class="grid-content bg-purple logo">
            <h1>XIAOKE图床</h1>
          </div>
        </el-col>
        <!-- 右侧按钮 -->
        <el-col :span="12">
          <div class="grid-content bg-purple menu">
            <div class="menu_item">
              <!-- 没有登陆之前显示 -->
              <div class="menu_item_box" v-if="isLogin">
                <div class="login" @click="LogindialogVisible = true">
                  <i class="el-icon-user-solid"></i>登陆
                </div>
                <div class="register" @click="RegisterdialogVisible = true">
                  <i class="el-icon-user"></i>注册
                </div>
              </div>
              <!-- 登陆成功的之后显示 -->
              <div class="menu_item_box" v-else>
                <div @click="control">
                  <i class="el-icon-s-tools"></i>控制台
                </div>
                <div @click="exitLogin"><i class="el-icon-error"></i>退出</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-header>
    <!-- 主体 -->
    <div class="main">
      <div class="main_wrap">
        <!-- 上传容器 -->
        <p v-show="isannouncement" class="announcement">
          🔊&nbsp;&nbsp;网站由NODE语言编写应用Exoress框架开发，前端全部组件由VUE
          + Element ui框架编写。由作者个人更新维护，感谢使用者的支持。<span
            @click="announcement_btn_close"
            class="announcement_btn el-icon-close"
          ></span>
        </p>
        <div class="upload">
          <el-upload
            class="upload-demo"
            drag
            :action="defaults_url + '/fileupload'"
            multiple
            :headers="headers"
            :on-success="up_success"
            accept=".jpg,.png,.bmp,.gif,.ico,.pcx,.jpeg,.tif,.raw,.tga"
            :before-upload="before_upload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__text">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </div>
        <div class="menu_tabs" v-show="is_main_menu">
          <div class="tabs_header">
            <div class="tabs_header_container">
              <div
                v-for="(item, index) in TabsList"
                @click="tabs_click(index)"
                :key="index"
                :class="item.class"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
          <div class="tabs_container">
            <div
              class="tabs_container_item"
              v-if="this.TabsIndex === 0 ? true : false"
            >
              <div
                class="main_menu_item"
                v-for="(item, index) in fileList"
                :key="index"
              >
                <div class="menu_main_left">
                  <img :src="item.url" alt="" />
                </div>
                <div
                  :data-clipboard-text="item.url"
                  class="menu_main_right"
                  @click="img_copy"
                >
                  <span>{{ item.url }}</span>
                </div>
              </div>
            </div>
            <div
              class="tabs_container_item"
              v-if="this.TabsIndex === 1 ? true : false"
            >
              <div
                class="main_menu_item"
                v-for="(item, index) in fileList"
                :key="index"
              >
                <div class="menu_main_left">
                  <img :src="item.url" alt="" />
                </div>
                <div
                  :data-clipboard-text="'[img]' + item.url + '[/img]'"
                  class="menu_main_right"
                  @click="img_copy"
                >
                  <span>[img]{{ item.url }}[/img]</span>
                </div>
              </div>
            </div>
            <div
              class="tabs_container_item"
              v-if="this.TabsIndex === 2 ? true : false"
            >
              <div
                class="main_menu_item"
                v-for="(item, index) in fileList"
                :key="index"
              >
                <div class="menu_main_left">
                  <img :src="item.url" alt="" />
                </div>
                <div
                  :data-clipboard-text="
                    imgs +
                    item.url +
                    semicolon +
                    '   alt=' +
                    semicolon +
                    item.name +
                    semicolon +
                    '/>'
                  "
                  class="menu_main_right"
                  @click="img_copy"
                >
                  <span>
                    {{ imgs + item.url + '"' + `   alt="` + item.name + `"/>` }}
                  </span>
                </div>
              </div>
            </div>
            <div
              class="tabs_container_item"
              v-if="this.TabsIndex === 3 ? true : false"
            >
              <div
                class="main_menu_item"
                v-for="(item, index) in fileList"
                :key="index"
              >
                <div class="menu_main_left">
                  <img :src="item.url" alt="" />
                </div>
                <div
                  :data-clipboard-text="
                    '![' + item.name + '](' + item.url + ')'
                  "
                  class="menu_main_right"
                  @click="img_copy"
                >
                  <span>![{{ item.name }}]({{ item.url }})</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <div class="footer">
        © 2020 XIAOKE - All Rights Reserved<br />请勿上传违反中国大陆和香港法律的图片，违者后果自负.
      </div>
    </div>

    <!-- 登陆对话框 -->
    <el-dialog
      title="登陆"
      :visible.sync="LogindialogVisible"
      width="350px"
      :before-close="LoginhandleClose"
      class="loginDialog"
    >
      <el-form
        ref="LoginRefForm"
        :rules="LoginRules"
        :model="Loginform"
        label-width="auto"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="Loginform.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="Loginform.password"></el-input>
        </el-form-item>
        <el-button type="primary loginbtn" size="small" @click="Login"
          >登陆</el-button
        >
      </el-form>
    </el-dialog>

    <!-- 注册 -->
    <el-dialog
      title="注册"
      :visible.sync="RegisterdialogVisible"
      width="350px"
      :before-close="RegisterhandleClose"
      center
    >
      <el-form
        ref="RegisterRefForm"
        :rules="RegisternRules"
        :model="Registernform"
        label-width="auto"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="Registernform.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <div class="sendemail">
            <el-input
              type="email"
              class="sendemail_val"
              v-model="Registernform.email"
            ></el-input>
            <button
              @click="sendemail_click"
              :disabled="sendemail_btn"
              class="sendemail_btn"
            >
              {{ sendemail }}
            </button>
          </div>
        </el-form-item>
        <el-form-item label="验证码" prop="VerificationCode">
          <el-input
            type="email"
            v-model="Registernform.VerificationCode"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="Registernform.password"></el-input>
        </el-form-item>
        <el-form-item class="loginDialog">
          <el-button type="primary loginbtn" size="small" @click="Register"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 点击复制
import Clipboard from "clipboard";
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入正确的邮箱！"));
    };
    // 验证是否有中文
    var chenkUser = (rule, value, cb) => {
      const regEmail = /^[^\u4e00-\u9fa5]+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("用户名不能有中文！"));
    };
    return {
      // 上传组件 头部
      headers: {
        Authorization: sessionStorage.getItem("token") || null,
      },
      // 登陆表单对话框
      LogindialogVisible: false,
      // 登陆表单信息
      Loginform: {
        email: "",
        password: "",
      },
      // 对话框 宽度
      dialogWidht: "50%",
      // 登陆表单验证规则
      LoginRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      // 注册表单信息
      Registernform: {
        username: "",
        email: "",
        password: "",
        VerificationCode: "",
      },
      // 注册表单对话框
      RegisterdialogVisible: false,
      // 注册表单验证规则
      RegisternRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, message: "邮箱格式不正确", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: chenkUser, trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        VerificationCode: [
          { required: true, message: "请输入邮箱验证码", trigger: "blur" },
        ],
      },
      // 上传好的文件列表
      fileList: [],
      // img
      imgs: `<img src="`,
      isannouncement: true,
      semicolon: '"',
      sendemail: "获取验证码",
      sendemail_btn: false,
      TabsList: [
        {
          name: "URL",
          class: "tabs_header_item tabs_header_item_selected",
        },
        {
          name: "BBcode",
          class: "tabs_header_item",
        },
        {
          name: "HTML",
          class: "tabs_header_item",
        },
        {
          name: "Markdown",
          class: "tabs_header_item",
        },
      ],
      TabsIndex: 0,
    };
  },
  async created() {},
  methods: {
    // 登陆对话框关闭
    LoginhandleClose() {
      // 关闭对话框
      this.LogindialogVisible = false;
      // 重置表单
      this.$refs.LoginRefForm.resetFields();
    },
    // 登陆
    Login() {
      this.$refs.LoginRefForm.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请正确的填写表单！");
          return;
        }
        const { data: res } = await this.$http.post("/login", this.Loginform);
        if (res.meta.status != 200) {
          this.$message.error(res.meta.msg);
          return;
        }
        // 将用户信息存储在本地
        window.sessionStorage.setItem("userinfo", JSON.stringify(res.data));
        // 就token存储本地
        window.sessionStorage.setItem("token", res.data.token);
        this.$message.success("登陆成功！");
        // 关闭对话框
        this.LogindialogVisible = false;
        // 跳转后台管理
        this.$router.push("/index");
      });
    },
    // 退出登陆
    exitLogin() {
      this.$confirm("此操作将永久退出登陆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          sessionStorage.clear();
          location.reload();
        })

        .catch(() => {});
    },
    // 注册对话框关闭
    RegisterhandleClose() {
      this.$refs.RegisterRefForm.resetFields();
      this.RegisterdialogVisible = false;
    },
    // 注册
    async Register() {
      this.$refs.RegisterRefForm.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请正确的填写表单！");
          return;
        }
        const { data: res } = await this.$http.post(
          "/register",
          this.Registernform
        );
        if (res.meta.status != 201) {
          this.$message.error(res.meta.msg);
          return;
        }
        this.$message.success("注册成功！");
        this.RegisterdialogVisible = false;
      });
    },
    tabs_click(i) {
      this.TabsList.forEach((item) => {
        item.class = "tabs_header_item";
      });
      this.TabsList[i].class = "tabs_header_item tabs_header_item_selected";
      this.TabsIndex = i;
    },
    // 文件上传成功触发
    up_success(response, file, fileList) {
      if (response.meta.status != 200) {
        this.$message.error(response.meta.msg);
        return;
      }
      this.fileList.push(response.data);
    },
    // 文件上传之前的函数
    before_upload(file) {
      // return false;
      let filename = file.name;
      let reg = /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/;
      if (!reg.test(filename)) {
        this.$message.error("拒绝上传的文件类型！");
        return false;
      }
    },
    // 控制台 点击事件
    control() {
      this.$router.push("/index");
    },
    announcement_btn_close() {
      this.isannouncement = !this.isannouncement;
    },
    img_copy() {
      var clipboard = new Clipboard(".menu_main_right");
      clipboard.on("success", (e) => {
        this.$message.success("复制成功！");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        // 不支持复制
        this.$message.success("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },
    sendemail_click() {
      this.$refs.RegisterRefForm.validateField("email", async (valid) => {
        // console.log(valid);
        if (
          valid == "请输入邮箱" ||
          valid == "请输入正确的邮箱！" ||
          valid == "邮箱格式不正确"
        ) {
          // console.log(valid);
          return;
        }
        let email = this.Registernform.email;
        const { data: res } = await this.$http.post("sendemail", {
          recipient: email,
        });
        if (res.meta.status != 200) {
          this.$message.error("发送失败！");
          return;
        }

        this.$message.success("发送成功！");
        console.log(res);
        var sendemail_btn = document.querySelector(".sendemail_btn");
        sendemail_btn.style.background = "#999";
        var i = 1;
        var item = setInterval(() => {
          this.sendemail = `${i++}秒后重发`;
          this.sendemail_btn = true;
          if (i == 120) {
            this.sendemail = "获取验证码";
            this.sendemail_btn = false;
            clearInterval(item);
            sendemail_btn.style.background = "#409EFF";
          }
        }, 1000);
      });
    },
  },
  computed: {
    // 对话框宽度 计算函数
    clientWidth() {
      let clientWidth = document.documentElement.clientWidth;
      if (clientWidth < 768) {
        return "95%";
      } else {
        return "50%";
      }
    },
    // 判断是否登陆 函数
    isLogin() {
      let is = sessionStorage.getItem("token");
      if (is) {
        return false;
      }
      return true;
    },
    // 判断 是否 已经有上传文件 函数
    is_main_menu() {
      if (this.fileList.length == 0) {
        return false;
      }
      return true;
    },
  },
};
</script>

<style scoped>
.el-container {
  width: 100%;
  height: 100vh;
}
.header {
  background: #1e90ff;
  height: 60px !important;
}
.row-bg {
  max-width: 1200px;
  height: 100%;
  margin: auto;
}
.header .logo {
  height: 100%;
}
.header .logo h1 {
  font-size: 18px;
  color: #fff;
  line-height: 60px;
}
.header .menu {
  height: 100%;
  display: flex;
  /* 右对齐 */
  justify-content: flex-end;
  line-height: 60px;
  color: #fff;
}
.header .menu i {
  font-size: 14px;
  margin: 0 3px;
}
.menu .menu_item {
  display: flex;
  cursor: pointer;
}
.menu .menu_item .menu_item_box {
  display: flex;
}
.menu .menu_item .menu_item_box div:nth-child(1) {
  margin-right: 15px;
}
.menu .menu_item .menu_item_box div:nth-child(2) {
  margin-right: 5px;
}
.loginbtn {
  width: 70%;
  height: 40px;
}
.loginDialog {
  text-align: center;
}
.main {
  width: 100%;
  margin: 0;
  padding: 0;
}
.main .main_wrap {
  max-width: 1200px;
  height: 100%;
  margin: auto;
}
.upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 50vh;
  margin-top: 20px;
  box-sizing: border-box;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 5px;
}
.el-upload-dragger {
  width: 200px !important;
  border: 1px solid red !important;
  background: #000 !important;
}
.announcement {
  position: relative;
  margin: 10px 0px;
  padding: 13px 20px;
  background: #e0fcff;
  color: #007785;
  border-radius: 5px;
  line-height: 25px;
}
.announcement_btn {
  cursor: pointer;
  position: absolute;
  color: #333;
  top: 5px;
  right: 10px;
}
.tabs {
  height: 100%;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  margin-top: 20px;
  padding-top: 10px;
}
.tbas_title {
  position: relative;
  margin: 20px 0;
  font-size: 20px;
  height: 30px;
  color: #222;
  text-align: center;
  text-transform: uppercase;
}
.tbas_title::after {
  position: absolute;
  content: "";
  height: 2px;
  width: 50px;
  background: #2775ff;
  top: 100%;
  left: 50%;
  transform: translate(-50%, 0%);
}
.main_menu_item {
  display: flex;
}

.menu_main_left {
  box-sizing: border-box;
  padding: 5px;
  width: 230px !important;
  height: 100%;
  overflow: hidden;
}
.menu_main_left img {
  width: 100%;
  border-radius: 3px;
}
.menu_main_right {
  display: flex;
  flex: 1;
  align-items: center;
  font-size: 14px;
  padding: 0 15px;
  color: #4e4e4e;
  cursor: pointer;
}
.footer {
  margin-top: 45px;
  width: 100%;
  height: 6vh !important;
  color: #4e4e4e;
  font-size: 12px;
  text-align: center;
}
.sendemail {
  width: 100%;
  margin: 0;
  padding: 0;
  text-align: none;
}
.sendemail_val {
  width: 71%;
  margin-right: 2%;
}
.sendemail_btn {
  outline: none;
  width: 25%;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border: 0;
  border-radius: 5px;
  color: #fff;
  background: #409eff;
  font-size: 10px;
}
.menu_tabs {
  margin-top: 20px;
  width: 100%;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 5px;
}
.tabs_header {
  display: flex;
  height: 55px;
  justify-content: center;
  align-items: center;
}
.tabs_header_container {
  display: flex;
  height: 100%;
}
.tabs_header_item {
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin: 0 15px;
}
.tabs_header_item_selected {
  color: #1e90ff;
}
.tabs_header_item_selected::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, 0);
  width: 80%;
  height: 2px;
  background: #1e90ff;
}
.tabs_container {
  width: 100%;
  height: 100%;
}
.tabs_container_item {
  width: 100%;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
}
</style>
